#include"SList.h"

void SLTPrint(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* pnewnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (!pnewnode)
	{
		perror("malloc fail!");
		exit(1);
	}
	pnewnode->data = x;
	pnewnode->next = NULL;
	return pnewnode;
}

void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* pnewnode = SLTBuyNode(x);
	
	if (!*pphead)
	{
		*pphead = pnewnode;
	}
	else
	{
		SLTNode* ptail = *pphead;
		while (ptail->next)
		{
			ptail = ptail->next;
		}
		//ptail pnewnode
		ptail->next = pnewnode;
	}
}
void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* pnewnode = SLTBuyNode(x);

	//*pphead pnewnode
	pnewnode->next = *pphead;
	*pphead = pnewnode;
}

void SLTPopBack(SLTNode** pphead) 
{
	assert(pphead && *pphead);
	if (!(*pphead)->next)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* prev = *pphead;
		SLTNode* ptail = (*pphead)->next;
		while (ptail->next)
		{
			ptail = ptail->next;
			prev = prev->next;
		}
		//prev ptail NULL
		free(ptail);
		ptail = NULL;

		prev->next = NULL;
	}

}
void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	//*pphead next
	SLTNode* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

void SLTInsertFront(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead && *pphead && pos);
	if (pos == *pphead)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* pnewnode = SLTBuyNode(x);
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{

			prev = prev->next;
		}
		//prev pnewnode pos
		pnewnode->next = pos;
		prev->next = pnewnode;
	}
}
void SLTEraseFront(SLTNode** pphead, SLTNode* pos);

void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && *pphead && pos);
	if (*pphead == pos)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		//prev pos next
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLTInsertBack(SLTNode* pos, SLTDataType x)
{
	assert(pos);
	SLTNode* pnewnode = SLTBuyNode(x);
	//pos pnewnode next
	pnewnode->next = pos->next;
	pos->next = pnewnode;
}

void SLTEraseBack(SLTNode* pos) 
{
	assert(pos);
	if (!pos->next->next)
	{
		free(pos->next);
		pos->next = NULL;
	}
	else
	{
		SLTNode* next = pos->next;
		pos->next = pos->next->next;
		free(next);
		next = NULL;
	}
	//pos next next->next
}

void SLTDestroy(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* tmp = NULL;
	while (tmp = (*pphead)->next)
	{
		free(*pphead);
		*pphead = tmp;
	}
	free(*pphead);
	*pphead = NULL;
	//*pphead next
}